package com.atguigu.lease.web.admin.custom.interceptors;

import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * projectName: com.atguigu.lease.web.admin.custom.interceptors
 *
 * @author: 顾司羽
 * time: 2024/12/14 1:18 周六
 * description: 编写HandlerInterceptor
 */
@Component
public class LoginProtectHandlerInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取request中请求头的token (约定好， 请求头， key是固定：access_token) ， 没有直接抛出： 没有登录
        String accessToken = request.getHeader("access_token");
        //2.检查token是否为null
        if (ObjectUtils.isEmpty(accessToken)){
            //没有token 没有登录
            throw new LeaseException(ResultCodeEnum.ADMIN_LOGIN_AUTH);
        }
        //3.检查token是否过期和有效以及是否被篡改
        JwtUtil.parseToken(accessToken);
        //true放行 | false拦截  [if(! preHandler()) return ;]
        return true;
    }
}
